/**
 * User domain class.
 */
class User {
    SortedSet commitments
	static transients = ['pass', 'admin', 'balance']
	static hasMany = [authorities: Role, commitments: Commitment]
	static belongsTo = Role

    def commitmentService

	/** Username = email*/
	String username

    String firstName
    String lastName
	/** MD5 Password */
	String passwd
	/** enabled */
	boolean enabled

	/** plain password to create a MD5 password */
	String pass = '[secret]'

    /*
     * Adres użytkownika nie jest wymagany.
     * Przydatny od wysyłania przedmiotów wylicytowanych na aukcjach.
     */
    String street
    String city
    String zipCode

	static constraints = {
		username(blank: false, unique: true, email:true)
        firstName(blank: false)
        lastName(blank: false)
		passwd(blank: false)
		enabled()
        street(nullable: true)
        city(nullable: true)
        zipCode(nullable: true,
            validator: {val, obj ->
                if (val) {
                    return val ==~ /[0-9][0-9]-[0-9][0-9][0-9]/
                }
            }
        )
	}

    /**
     * Zwraca saldo konta użytkownika (ilość brykietów)
     */
    int getBalance() {
        commitmentService.getBalanceForUser(this)
    }

    boolean isAdmin() {
        def admin = Role.findByAuthority("ROLE_ADMIN")
        authorities.contains(admin)
    }

    String toString() {
        "$firstName $lastName"
    }
}
